package org.rcy.framework.rpc.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.instrument.IllegalClassFormatException;

public class ServiceClassResolver {
	
	private static final Logger logger = LoggerFactory.getLogger(ServiceClassResolver.class);

	public static Class<?> resolve(Object serviceImpl) throws IllegalClassFormatException {
		Class<?>[] interfaces = serviceImpl.getClass().getInterfaces();
		if (isSpringProxy(serviceImpl)) {
			interfaces = serviceImpl.getClass().getSuperclass().getInterfaces();
		}
		// 必须实现接口
		if (interfaces.length == 0) {
			throw new IllegalClassFormatException("service should have at least one interface");
		}
		// 默认暴露第一个接口
		Class<?> serviceClass = interfaces[0];
		logger.info("Find serviceInterface [{}] for {}", serviceClass, serviceImpl);
		return serviceClass;
	}
	
	private static boolean isSpringProxy(Object object) {
		try {
			Class springProxy = Class.forName("org.springframework.aop.SpringProxy");
			return springProxy.isAssignableFrom(object.getClass());
		} catch (ClassNotFoundException e) {
			return false;
		}
	}

}
